package com.dcjt.firehotcarpad.utils;

import android.content.Context;
import android.os.Environment;

import com.aries.library.fast.retrofit.FastObserver;
import com.aries.ui.widget.progress.UIProgressView;
import com.dcjt.firehotcarpad.R;
import com.dcjt.firehotcarpad.base.App;
import com.dcjt.firehotcarpad.retrofit1.repository.ApiRepository1;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.io.File;
import java.lang.reflect.Field;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

//文件管理类
public class FileUtils {

    private static final String TAG = "FileUtils";

    public static class FilePath {
        public static final String ROOT_PATH = "Emergent/";
        public static final String RECORD_DIR = "record/";
        public static final String RECORD_PATH = ROOT_PATH + RECORD_DIR;
    }

    //获取文件存放根路径
    public static File getAppDir(Context context) {
        String dirPath = "";
        //SD卡是否存在
        boolean isSdCardExists = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
        boolean isRootDirExists = Environment.getExternalStorageDirectory().exists();
        if (isSdCardExists && isRootDirExists) {
            dirPath = String.format("%s/%s/", Environment.getExternalStorageDirectory().getAbsolutePath(), FilePath.ROOT_PATH);
        } else {
            dirPath = String.format("%s/%s/", context.getApplicationContext().getFilesDir().getAbsolutePath(), FilePath.ROOT_PATH);
        }

        File appDir = new File(dirPath);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        return appDir;
    }

    //获取录音存放路径
    public static File getAppRecordDir(Context context) {
        File appDir = getAppDir(context);
        File recordDir = new File(appDir.getAbsolutePath(), FilePath.RECORD_DIR);
        if (!recordDir.exists()) {
            recordDir.mkdir();
        }
        return recordDir;
    }

    //上传文件
    public static void upLoadFile(RxAppCompatActivity context,
                                  File file,
                                  LoadFileListener loadFileListener) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
        MultipartBody body = builder.build();
        UIProgressView progressView = new UIProgressView(context).setMessage("上传中...");
        progressView.show();
        progressView.setCancelable(false);
        ApiRepository1.getInstance().upLoadFile(body)
                .compose(context.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new FastObserver<List<String>>() {
                    @Override
                    public void _onNext(List<String> entity) {
                        progressView.dismiss();
                        if (entity != null) {
                            loadFileListener.onSuccess(entity);
                        } else {
                            loadFileListener.onError("上传文件出错");
                        }
                    }

                    @Override
                    public void _onError(int errorRes, int errorCode, Throwable e) {
                        super._onError(errorRes, errorCode, e);
                        e.printStackTrace();
                        progressView.dismiss();
                        loadFileListener.onError("上传文件出错");
                    }
                });
    }

    /**
     * 根据图片名字加载图片
     * @param name
     * @return
     */
    public static int getImgResourceForName1(String name){
        Class drawable = R.drawable.class;
        Field field = null;
        try {
            field =drawable.getField(name);
            int images = field.getInt(field.getName());
            return images;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static int getImgResourceForName(String imageName){

        Context ctx= App.get();
        int resId = ctx.getResources().getIdentifier(imageName, "drawable" , ctx.getPackageName());
        return resId;
    }

    public interface LoadFileListener {
        void onSuccess(List<String> url);

        void onError(String errMsg);
    }
}
